package com.example.springcloudwinter.service;


import com.example.springcloudwinter.bo.UserBo;
import com.example.springcloudwinter.dto.ResultEntity;
import com.example.springcloudwinter.feign.VIPFeignClient;
import com.example.springcloudwinter.mapper.UserMapper;
import com.example.springcloudwinter.po.UserPo;
import com.example.springcloudwinter.token.AuthenticationToken;
import com.example.springcloudwinter.util.VerifyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private AuthenticationToken jwtAuthenticationToken;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VIPFeignClient vipMapper;

    public ResultEntity<?> login(String userId, String password) {
        ResultEntity<Map<String,String>> result=new ResultEntity<>();
        Logger logger=LoggerFactory.getLogger(getClass());
        logger.info(userId);

        if (userMapper.login(userId,password)==0){
            return result.setCode(400);
        }

        Map<String,String> jwtMap=new HashMap<>();
        Map<String,Object> jwtPayload=new HashMap<>();
        jwtPayload.put("userId",userId);//jwtPayLoad是包含userId的jwt参数组
        jwtMap.put("JWT",jwtAuthenticationToken.getToken(jwtPayload));//根据参数组构建jwt字符串并返回给前端，作为一个有时间限制的登录凭证

        result.setCode(200).setDetail(jwtMap);
        return result;
    }
    public ResultEntity<?> register(String nickname, String password, String phoneNumber, int sex) {
        ResultEntity<?> result=new ResultEntity<>();
        if (phoneNumber.length() != 11 || !VerifyUtil.verifyPhoneNumber(phoneNumber))
            return result.setCode(501);
        if(userMapper.isUserIdExisted(phoneNumber)!=0)
            return result.setCode(502);
        userMapper.insertUser(phoneNumber,password,nickname,sex);
        return result.setCode(200);
    }

    public ResultEntity<?> getUserById(String userId) {
        ResultEntity<UserBo> result=new ResultEntity<>();
        try {
            UserPo userPo=userMapper.getUserById(userId);
            if (userPo == null){
                return result;
            }
            UserBo userBo=new UserBo(userPo);

            ResultEntity<Boolean> isVip = vipMapper.checkVIPByUserId(userId);
            if (isVip.getCode()!=200){
                return result;
            }
            userBo.setVipFlag(isVip.getDetail());
            result.setDetail(userBo).setCode(200);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }
}


